package queues;

import helpers.CrawlerHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cronjobs.CronAutoSitePageNews;

import services.Blogger;
import services.WordPress;

import models.AutoSite;
import models.Blog;
import models.MessageQueue;
import models.News;

import data.AutoSiteData;
import data.BlogData;
import data.MessageQueueData;
import debugs.AutoSiteDebug;
import debugs.NewsDebug;

public class QueueCrawlerNews extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(QueueCrawlerNews.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		log.setLevel(Level.FINE);
		String queueId = (String) URLDecoder.decode(request.getParameter("queueid"));
		MessageQueueData mData = new MessageQueueData();
		MessageQueue mq = mData.getById(queueId);
		
		if (mq != null) {
			AutoSiteData aData = new AutoSiteData();
			AutoSite autoSite = aData.getById(mq.getAutoSiteId());
			News news = CrawlerHelper.getNews(mq.getUrl(), autoSite);
			NewsDebug.debug(news);
			
			//update isDone is true in messageQueue
			mq.setIsDone(true);
			mData.insert(mq);
			
			//Post news to blogger
			BlogData blogData = new BlogData();
			Blog blog = blogData.getById(autoSite.getBlogId());
			
			if (blog.getType() != null && blog.getType().equalsIgnoreCase("wordpress")) {
				WordPress wp = new WordPress(blog);
					try {
					wp.createPost(news);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				Blogger blogger = new Blogger(blog);
				try {
					blogger.createPost(news);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			response.setContentType("text/html");
			NewsDebug.debugWeb(news, response);
			response.getWriter().println("Update success");
			log.info("Update succes");
			
		}
		
	}
}
